<?php

declare (strict_types=1);

namespace think\admin\service;

use think\admin\Exception;
use think\admin\Service;

/**
 * 多网关支持短信接口服务
 * Class SmsService
 * @package think\admin\service
 */
class SmsService extends Service
{
    /**
     * 验证手机短信验证码
     * @param string $phone 手机号码
     * @param integer $wait 等待时间
     * @return array
     * @throws Exception
     */
    public function sendVerifyCode(string $phone, int $wait = 120): array
    {
        $time = time();
        $engine = sysconfig('SYS_BASE', 'SQM_SYS_DEFAULT_SMS_ENGINE');
        $template = $engine === 'TENCENT' ? '1791221' : 'SMS_460795078';
        // 检查是否已经发送
        $cache = $this->app->cache->get($ckey = md5("code-{$template}-{$phone}"), []);
        if (is_array($cache) && isset($cache['time']) && $cache['time'] + $wait > $time) {
            $dtime = $cache['time'] + $wait < $time ? 0 : $cache['time'] + $wait - $time;
            return [1, '短信验证码已经发送！', ['time' => $dtime]];
        }
        // 生成新的验证码
        $code = (string)rand(100000, 999999);
        $this->app->cache->set($ckey, ['code' => $code, 'time' => $time], 600);
        // 尝试发送短信内容
        //$content = '您的验证码为 {code} ，该验证码5分钟内有效，请勿泄露于他人。';

        if ($engine === 'TENCENT') {
            $state = TencentSmsService::instance()->singleSendSms($phone, '', '', $template, $code);
        } elseif ($engine === 'ALIYUN') {
            $state = AlibabaSmsService::instance()->singleSendSms($phone, '', $template, json_encode(['code' => $code]));
        } else {
            $state = false;
        }
        if ($state) {
            return [1, '短信验证码发送成功！', ['time' => $wait]];
        } else {
            $this->app->cache->delete($ckey);
            return [0, '短信发送失败，请稍候再试！', ['time' => 0]];
        }
    }

    /**
     * 验证手机短信验证码
     * @param string $code
     * @param string $phone
     * @return bool
     * @throws Exception
     */
    public function checkVerifyCode(string $code, string $phone): bool
    {
        $engine = sysconfig('SYS_BASE', 'SQM_SYS_DEFAULT_SMS_ENGINE');
        $template = $engine === 'TENCENT' ? '1791221' : 'SMS_460795078';
        $cache = $this->app->cache->get($ckey = md5("code-{$template}-{$phone}"), []);
        if (is_array($cache) && isset($cache['code']) && $cache['code'] == $code) {
            $this->app->cache->delete($ckey);
            return true;
        } else {
            return false;
        }
    }
}